package org.example.forum.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.common.StringUtils;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.User;
import org.example.forum.service.IUserService;

import org.example.forum.utils.MD5Util;
import org.example.forum.utils.UUIDUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
 class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        if(user==null) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL)) ;

        }
        User newUser =userMapper.selectByUserName(user.getUsername());
        if(newUser!=null) {
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
          if(user.getGender()==null) user.setGender((byte)0);
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if(row!=1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        log.info("新增用户成功");
    }

    @Override
    public User selectByUserName(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public User selectById(Long Id) {
        if(Id==null||Id<=0) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
     return userMapper.selectByPrimaryKey(Id);
    }

    @Override
    public void modifyInfo(User user) {
        log.info("user:{}",user.toString());
        if(user.getId()==null||user.getId()<=0) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser==null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User existsUser1 = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser1==null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        boolean check;
        check = false;
        if(!StringUtils.isEmpty(user.getUsername()) &&!user.getUsername().equals(existsUser.getUsername())) {
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null) {
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            check=true;
        }

        // 9.校验邮箱
        if (!StringUtils.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            //设置邮箱
            updateUser.setEmail(user.getEmail());
            //更新标志位
            check = true;
        }
        // 9.校验电话号码
        if (!StringUtils.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            //设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            check = true;
        }
        // 10.校验个⼈简介
        if (!StringUtils.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            //设置电话号码
            updateUser.setRemark(user.getRemark());
            //更新标志位
            check = true;
        }
       if(!StringUtils.isEmpty(user.getNickname())&&!user.getNickname().equals(existsUser.getNickname())) {
           updateUser.setNickname(user.getNickname());
           check = true;
       }
        if(!check) {
            log.info("update:{}",updateUser.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row= userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.info(updateUser.toString());
            log.info("row{}",row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newpassword, String oldPassword) {
        if(id==null||id<=0){
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User existsUser = userMapper.selectByPrimaryKey(id);
        if(existsUser==null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String checkPasswprd= MD5Util.md5Salt(oldPassword,existsUser.getSalt());
        if(!checkPasswprd.equals(existsUser.getPassword())) {
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        String salt= UUIDUtil.UUID_32();
        String password= MD5Util.md5Salt(newpassword,salt);
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(password);
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(updateUser);

    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后，用户的发帖数是否小于0
        if (updateUser.getArticleCount() < 0) {
            // 如果小于0，则设置为0
            updateUser.setArticleCount(0);
        }

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

}
